<template>
  <a-modal
    title="新增海外仓产品"
    :width="1500"
    :maskClosable="false"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>

          <a-col :span="12" v-show="false">
            <a-form-item
              label="id"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入物料类型" v-decorator="['materialType', {rules: [{required: true, message: '请输入物料类型！'}]}]"/>
              <a-input placeholder="请输入成本价" v-decorator="['costPrice', {initialValue:0, rules: [{required: true, message: '请输入成本价！'}]}]"/>
              <a-input placeholder="请输入是否常用" v-decorator="['isCommon', {initialValue:'N', rules: [{required: true, message: '请输入是否常用！'}]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入名称" v-decorator="['materialName', {rules: [{required: true, message: '请输入名称！'}]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="料号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入料号" v-decorator="['materialCode', {rules: [{required: true, message: '请输入料号！'}]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="规格"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入规格" v-decorator="['materialModelNumber', {rules: [{required: true, message: '请输入规格！'}]}]"/>
            </a-form-item>
          </a-col>

          <!-- <a-col :span="12">
            <a-form-item
              label="分类"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入分类" v-decorator="['', {rules: [{required: true, message: '请输入分类！'}]}]"/>
            </a-form-item>
          </a-col> -->

          <a-col :span="12">
            <a-form-item
              label="归属公司"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-select v-decorator="['orgIdCompany', {rules: [{required: true, message: '请输入归属公司！'}]}]"
                        placeholder="请输入归属子公司">
                <a-select-option :value="id" v-for="{id, name} in companyList">
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="库存数量"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input-number :min="0" style="width: 100%" placeholder="请输入库存数量"
                              v-decorator="['inventoryNumber', {rules: [{required: true, message: '请输入库存数量！'}]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="预警值"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input-number :min="0" style="width: 100%" placeholder="请输入预警值"
                              v-decorator="['inventoryWarningValue', {rules: [{required: true, message: '请输入预警值！'}]}]"/>
            </a-form-item>
          </a-col>


          <a-col :span="12">
            <a-form-item
              label="仓库"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-select v-decorator="['orgIdStorehouse', {rules: [{required: true, message: '请输入仓库！'}]}]"
                        placeholder="请输入仓库" @change="changeStore">
                <a-select-option :value="id" v-for="{id, name} in storehouseList">
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="库位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-select v-decorator="['orgIdStorehousePosition', {rules: [{required: true, message: '请输入库位！'}]}]"
                        placeholder="请选择库位">
                <a-select-option :value="id" v-for="{id, name} in storehousePositionList">
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="库位备注"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入库位备注" v-decorator="['storehousePositionRemark', {rules: [{required: true, message: '请输入库位备注！'}]}]"/>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item
              label="图片"
              :labelCol="labelColBlock"
              :wrapperCol="wrapperColBlock"
              has-feedback=""
            >
              <a-input v-show="false" placeholder="请输入图片" v-decorator="['image', {rules: [{required: true, message: '请输入图片！'}]}]"/>
              <fc-upload :file-list="fileList" @change="(fileListString) =>{ form.setFieldsValue({image: fileListString}) }"/>
                <!-- <CropperUpload
                  @fcsuccess="fcsuccess"
                  avatarText=""
                /> -->
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item
              label="描述"
              :labelCol="labelColBlock"
              :wrapperCol="wrapperColBlock"
              has-feedback=""
            >
              <a-input placeholder="请输入内容" v-decorator="['description', {rules: [{required: true, message: '请输入描述！'}]}]"
                       type="textarea"/>
            </a-form-item>
          </a-col>

          <!--        自身BOM Table组件   -->
          <a-col :span="24">
            <a-form-item
              :validate-status="bomSelfValidate.validateStatus"
              :help="bomSelfValidate.errorMsg">
              <!--        复杂的BOM Table组件   -->
              <FCBomMaterialTable ref="bomMaterialTableSelf" :default-bom="bom"/>
            </a-form-item>
          </a-col>

          <!--    引入其它BOM    -->
          <a-col :span="24">
            <a-form-item>
              <reference-other-bom :on-bom-selected="onBomSelected"/>
            </a-form-item>
          </a-col>

          <!--        其它BOM Table组件   -->
          <a-col :span="24">
            <a-form-item v-for="(item, index) in otherBoms">
              <FCBomMaterialTable :ref="'bomMaterialTable'+index" :key="index" @delete="(key)=>otherBoms.splice(key,1)" :default-bom="item"/>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {listFull as emsBomMaterialListFull} from '@/api/modular/main/emsbommaterial/emsBomMaterialManage'
import {addOverseasProduct} from '@/api/modular/main/emsmaterial/emsMaterialManage'
import FcUpload from '@/components/FCUpload/FcUpload'
import FCBomMaterialTable from '@/views/main/emsbom/FCBomMaterialTable'
import {list as emsOrgList} from '@/api/modular/main/emsorg/emsOrgManage'
import ReferenceOtherBom from '@/components/FCReferenceOtherBom/ReferenceOtherBom'

export default {
  components: {
    ReferenceOtherBom,
    FCBomMaterialTable,
    FcUpload,

  },
  data() {
    return {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15}
      },
      labelColBlock: {
        xs: {span: 24},
        sm: {span: 3}
      },
      wrapperColBlock: {
        xs: {span: 24},
        sm: {span: 20}
      },
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      formModel: {},
      bomIndexVisible: false,
      //  table 组件
      bom: {
        bomId: '',
        bomCode: '',
        bomName: '本次BOM',
        bomType: '',
        status: '',
        image: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
        bomMaterials: [],
        otherBoms: [],
      },
      bomMaterial: {
        bomMaterialId: '',
        bomId: '',
        bomIdSource: '',
        bomMaterialSort: '',
        materialId: '',
        materialNumber: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
      },
      bomSelfValidate: {},
      otherBoms: [],
      selfBoms: [],
      fileList: [],
      orgIdStorehouse: null,
      sysOrgs: [],
      materialType: '',
      orgTree: [],
      // suppliers: [],
    }
  },
  computed: {
    companyList() {
      if (this.sysOrgs.length == 0) {
        return []
      }
      return this.sysOrgs.filter((org) => org.unitRanId == this.$businessEnum.ORG_TYPE_ENUM.COMPANY.id).map((org) => {
        return {id: org.id + '', name: org.name}
      })
    },
    storehouseList() {
      if (this.sysOrgs.length == 0) {
        return []
      }
      return this.sysOrgs.filter((org) => org.unitRanId == this.$businessEnum.ORG_TYPE_ENUM.STOREHOUSE.id).map((org) => {
        return {id: org.id + '', name: org.name}
      })
    },
    /**
     * 库位
     * @returns {{label: string, value: string}[]|*[]}
     */
    storehousePositionList() {
      const orgTypeId = this.$businessEnum.ORG_TYPE_ENUM.STOREHOUSE_POSITION.id
      const orgIdStorehouse = this.orgIdStorehouse
      return this.sysOrgs.filter((org) => {
        return org.unitRanId == orgTypeId && org.pid == orgIdStorehouse
      }).map((org) => {
        return {id: org.id + '', name: org.name}
      })
    },
  },
  methods: {
    fcsuccess(url){
        this.form.setFieldsValue({image: url})
      },
    add(record) {
      this.visible = true
      this.getSysOrgs()

      setTimeout(() => {
        this.form.resetFields()
        this.form.setFieldsValue(record)
        this.orgIdStorehouse = null
        this.createOrderNumber()
      }, 100)
    },
    changeStore(value){
      this.orgIdStorehouse = value;
      this.form.setFieldsValue({
        orgIdStorehousePosition:''
      })
    },
     // 打开弹框时候生成一个单号
    createOrderNumber(){
          var d = new Date()
          var year = d.getFullYear()
          var month = d.getMonth()
          month = month + 1 > 12 ? 1 : month + 1
          month =  month > 9 ? month : "0" +month.toString()
          var day = d.getDate()
          day = day > 9 ? day : "0" + day.toString()
          var hour = d.getHours()
          hour = hour > 9 ? hour : "0" + hour.toString()
          var minute = d.getMinutes()
          minute = minute > 9 ? minute : "0" + minute.toString()
          var second = d.getSeconds()
          second = second > 9 ? second : "0" + second.toString()

          let num = parseInt(Math.random()*100000).toString()
          // 如果随机数长度不够5位,则在后面补0,够5位为止
          for(let i=num.length; i<5; i++){ num+='0' }

          // let header = this.type==this.ORDER_TYPE_ENUM.inOrder.id?'WDRK': this.type==this.ORDER_TYPE_ENUM.outOrder.id?'WDCK':''

          let scOrderNo = 'LH' + year+month+day+hour+minute+second + num

          this.form.setFieldsValue({materialCode: scOrderNo})
    },
    handleSubmit() {
      this.getSelfBomMaterialValue()
      const {form: {validateFields}} = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        this.confirmLoading = false
        this.otherBoms.forEach(emsBomParam => {
          emsBomParam.bomId = null
          emsBomParam.bomMaterials.forEach(emsBomMaterialParam => {
            emsBomMaterialParam.bomId = null
          })
        })
        if (!errors) {
          values = Object.assign({bom: {bomMaterials: this.selfBoms, otherBoms: this.otherBoms}}, values)
          addOverseasProduct(values).then((res) => {
            this.confirmLoading = false
            if (res.success) {
              this.$message.success('新增成功')
              this.handleCancel()
              this.$emit('ok', values)
            } else {
              this.$message.info('新增失败：' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
      this.fileList = []
      this.bom = {
        bomId: '',
        bomCode: '',
        bomName: '本次BOM',
        bomType: '',
        status: '',
        image: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
        bomMaterials: [],
        otherBoms: [],
      }
      this.otherBoms = []
    },
    getSysOrgs() {
      emsOrgList().then((res) => {
        this.sysOrgs = res.data
      })
    },

    // upload
    handleFileListStringChange(fileListString) {
      this.form.setFieldsValue({image: fileListString})
    },
    onBomSelected(selectedBomArray) {
      console.log(`selectedBomArray:${JSON.stringify(selectedBomArray)}`)
      // 新增其它BOM,生成表格控件。数据结构为 bom，其中还需要建立关联的原料数组。
      // 同时还需要处理该BOM引用了多个原料或别的BOM的情况
      // // 表格里面显示BOM中包含的原料列表
      // 不管是普通BOM，还是组合BOM。都将引用的BOM中的原料放进同一张表中
      // 构建BOM数据
      if (selectedBomArray.length == 0) {
        this.$message.error('没有选择BOM')
        return
      }
      if (selectedBomArray.length > 1) {
        this.$message.error('暂不支持多选BOM添加')
        return
      }
      if (selectedBomArray.length > 0) {
        let selectedBom = selectedBomArray[0]
        let bomIdSource = selectedBom.bomId
        emsBomMaterialListFull({bomIdSource}).then(res => {
          let bomMaterials = res.data
          // 构建BOM Bean
          selectedBom.bomMaterials = bomMaterials
          this.otherBoms.push(selectedBom)
        })
      }
    },
    getSelfBomMaterialValue() {
      let tableValue = this.$refs.bomMaterialTableSelf.getTableValue()
      this.selfBoms = tableValue

      if (tableValue && tableValue.length > 0) {
        this.bomSelfValidate = {
          validateStatus: 'success',
          errorMsg: null,
        }
      } else {
        this.bomSelfValidate = {
          validateStatus: 'error',
          errorMsg: '物料清单不能为空',
        }
      }

      this.getBomTableValue()
    },
    getBomTableValue() {
      // bomMaterialTable
      for (let i = 0; i < this.otherBoms.length; i++) {
        let $refTable = this.$refs['bomMaterialTable' + i][0]
        this.otherBoms[i] = $refTable.getBom()
      }
      // for (const refsKey in this.$refs) {
      //   if (refsKey.startsWith('bomMaterialTable')) {
      //     let $refTable = this.$refs[refsKey]
      //     this.otherBoms.push($refTable.getTableValue())
      //   }
      // }
    },
    handleEmsMaterialIndex1Show() {
      this.$refs.emsMaterialIndex1.show()
    },
    onEmsMaterialIndex1Selected(materialRow) {
      // console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
      let {materialId, materialName, materialCode, materialType, costPrice} = materialRow
      this.form.setFieldsValue({output: materialId})
      this.formModel = Object.assign({}, this.formModel, {output: materialId, outputObject: materialRow})
    },
  },


  // upload
  handleFileListStringChange(fileListString) {
    this.form.setFieldsValue({image: fileListString})
  },
  onBomSelected(selectedBomArray) {
    console.log(`selectedBomArray:${JSON.stringify(selectedBomArray)}`)
    // 新增其它BOM,生成表格控件。数据结构为 bom，其中还需要建立关联的原料数组。
    // 同时还需要处理该BOM引用了多个原料或别的BOM的情况
    // // 表格里面显示BOM中包含的原料列表
    // 不管是普通BOM，还是组合BOM。都将引用的BOM中的原料放进同一张表中
    // 构建BOM数据
    if (selectedBomArray.length == 0) {
      this.$message.error('没有选择BOM')
      return
    }
    if (selectedBomArray.length > 1) {
      this.$message.error('暂不支持多选BOM添加')
      return
    }
    if (selectedBomArray.length > 0) {
      let selectedBom = selectedBomArray[0]
      let bomIdSource = selectedBom.bomId
      emsBomMaterialListFull({bomIdSource}).then(res => {
        let bomMaterials = res.data
        // 构建BOM Bean
        selectedBom.bomMaterials = bomMaterials
        this.otherBoms.push(selectedBom)
      })
    }
  },
  getSelfBomMaterialValue() {
    let tableValue = this.$refs.bomMaterialTableSelf.getTableValue()
    this.selfBoms = tableValue

    if (tableValue && tableValue.length > 0) {
      this.bomSelfValidate = {
        validateStatus: 'success',
        errorMsg: null,
      }
    } else {
      this.bomSelfValidate = {
        validateStatus: 'error',
        errorMsg: '物料清单不能为空',
      }
    }

    this.getBomTableValue()
  },
  getBomTableValue() {
    // bomMaterialTable
    for (let i = 0; i < this.otherBoms.length; i++) {
      let $refTable = this.$refs['bomMaterialTable' + i][0]
      this.otherBoms[i] = $refTable.getBom()
    }
    // for (const refsKey in this.$refs) {
    //   if (refsKey.startsWith('bomMaterialTable')) {
    //     let $refTable = this.$refs[refsKey]
    //     this.otherBoms.push($refTable.getTableValue())
    //   }
    // }
  },
  handleEmsMaterialIndex1Show() {
    this.$refs.emsMaterialIndex1.show()
  },
  onEmsMaterialIndex1Selected(materialRow) {
    // console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
    let {materialId, materialName, materialCode, materialType, costPrice} = materialRow
    this.form.setFieldsValue({output: materialId})
    this.formModel = Object.assign({}, this.formModel, {output: materialId, outputObject: materialRow})
  },
  emiShow() {
    this.$refs.emsMaterialIndex2.show()
  }
}
</script>
